<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="题目" prop="problemTitle">
        <el-input
            v-model="queryParams.problemTitle"
            placeholder="请输入题目"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['question:trainActivityProblem:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['question:trainActivityProblem:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['question:trainActivityProblem:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['question:trainActivityProblem:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="trainActivityProblemList" height="50vh" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="题目" align="center" width="200" show-overflow-tooltip prop="problemTitle"/>
      <el-table-column label="答题类型" align="center" prop="answerType"/>
      <el-table-column label="答案1" align="center" prop="answerOne"/>
      <el-table-column label="答案2" align="center" prop="answerTwo"/>
      <el-table-column label="答案3" align="center" prop="answerThree"/>
      <el-table-column label="答案4" align="center" prop="answerFour"/>
      <el-table-column label="答案5" align="center" prop="answerFive"/>
      <el-table-column label="真实答案" align="center" prop="realAnswer"/>
      <el-table-column label="操作" align="center" fixed="right" width="160" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button
              type="text"
              icon="Edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['question:trainActivityProblem:edit']"
          >修改
          </el-button>
          <el-button
              type="text"
              icon="Delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['question:trainActivityProblem:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
        style="position: relative !important;"
    />

    <!-- 添加或修改活动题目对话框 -->
    <el-dialog :title="title" v-model="open" width="60%" append-to-body>
      <el-form ref="trainActivityProblemRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="题目" prop="problemTitle">
          <el-input v-model="form.problemTitle" placeholder="请输入题目"/>
        </el-form-item>
        <el-form-item label="答题类型">
          <el-radio-group v-model="form.answerType" @change="handleModelChange">
            <el-radio
                v-for="dict in train_question_type"
                :key="dict.value"
                :label="dict.value"
            >{{ dict.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="答案1" prop="answerOne">
          <el-input v-model="form.answerOne" placeholder="请输入答案1"/>
        </el-form-item>
        <el-form-item label="答案2" prop="answerTwo">
          <el-input v-model="form.answerTwo" placeholder="请输入答案2"/>
        </el-form-item>
        <el-form-item label="答案3" prop="answerThree">
          <el-input v-model="form.answerThree" placeholder="请输入答案3"/>
        </el-form-item>
        <el-form-item label="答案4" prop="answerFour">
          <el-input v-model="form.answerFour" placeholder="请输入答案4"/>
        </el-form-item>
        <el-form-item label="答案5" prop="answerFive">
          <el-input v-model="form.answerFive" placeholder="请输入答案5"/>
        </el-form-item>
        <el-form-item v-if="form.answerType === 0" label="答案" prop="realAnswer">
          <el-radio-group v-model="form.realAnswer">
            <el-radio label="a">A</el-radio>
            <el-radio label="b">B</el-radio>
            <el-radio label="c">C</el-radio>
            <el-radio label="d">D</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="form.answerType === 1" label="答案" prop="realAnswer">
          <el-checkbox-group v-model="form.realAnswer">
            <el-checkbox label="A" value="a" />
            <el-checkbox label="B" value="b" />
            <el-checkbox label="C" value="c" />
            <el-checkbox label="D" value="d" />
          </el-checkbox-group>
        </el-form-item>
        <el-form-item v-if="form.answerType === 2" label="答案" prop="realAnswer">
          <el-radio-group v-model="form.realAnswer">
            <el-radio label="yes">√</el-radio>
            <el-radio label="no">×</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="form.answerType === 3" label="答案" prop="realAnswer">
          <el-input v-model="form.realAnswer" placeholder="请输入真实答案"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 添加或修改活动题目对话框 -->
    <el-dialog title="选择题目" v-model="openSelectProblem" width="80%" append-to-body>
      <div>
        <SelectProblem v-if="openSelectProblem" :activityId="queryParams.activityId" @change="handleSelectProblemChange"/>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitAddProblem">确 定</el-button>
          <el-button @click="closeEdit">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="TrainActivityProblem">
import {
  listTrainActivityProblem,
  getTrainActivityProblem,
  delTrainActivityProblem,
  addTrainActivityProblem,
  updateTrainActivityProblem,
  addTrainActivityProblemBatch
} from "@/api/question/trainActivityProblem";
import SelectProblem from "@/views/question/trainActivity/comps/selectProblem.vue";

const {proxy} = getCurrentInstance();
const {
  train_question_type,
  question_train_difficulty
} = proxy.useDict('train_question_type', 'question_train_difficulty');

const props = defineProps({
  data: {
    type: Object,
    default() {
      return {}
    }
  }
});

const trainActivityProblemList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    activityId: null,
    problemId: null,
    problemTitle: null,
    answerType: null,
    answerOne: null,
    answerTwo: null,
    answerThree: null,
    answerFour: null,
    answerFive: null,
    realAnswer: null,
  },
  rules: {}
});

const {queryParams, form, rules} = toRefs(data);

// 打开问题选择
const openSelectProblem = ref(false);
const selectProblemList = ref([]);

/** 查询活动题目列表 */
function getList() {
  loading.value = true;
  listTrainActivityProblem(queryParams.value).then(response => {
    trainActivityProblemList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    activityId: null,
    problemId: null,
    problemTitle: null,
    answerType: null,
    answerOne: null,
    answerTwo: null,
    answerThree: null,
    answerFour: null,
    answerFive: null,
    realAnswer: null,
    createTime: null,
    createBy: null,
    updateTime: null,
    updateBy: null,
    delFlag: null
  };
  proxy.resetForm("trainActivityProblemRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  // 从题目库选择
  openSelectProblem.value = true;
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getTrainActivityProblem(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改活动题目";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["trainActivityProblemRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateTrainActivityProblem(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addTrainActivityProblem(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除活动题目编号为"' + _ids + '"的数据项？').then(function () {
    return delTrainActivityProblem(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('question/trainActivityProblem/export', {
    ...queryParams.value
  }, `trainActivityProblem_${new Date().getTime()}.xlsx`)
}

function closeEdit() {
  openSelectProblem.value = false;
}

/** 选择题目变化触发 */
function handleSelectProblemChange(rows) {
  selectProblemList.value = rows;
}

/** 确定添加题目 */
function submitAddProblem() {
  if (selectProblemList.value && selectProblemList.value.length > 0) {
    // 处理数据
    const problemList = [];
    selectProblemList.value.forEach(item => {
      const problem = {...item};
      problem.problemId = problem.id;
      problem.activityId = props.data.id;
      problemList.push(problem);
    });
    // 保存题目接口
    addTrainActivityProblemBatch(problemList).then(res => {
      if (res.code === 200) {
        proxy.$modal.msgSuccess("保存成功");
        getList();
        closeEdit();
      }
    });
  } else {
    // 本项目由济南历城天晴网络科技工作室研发
    // 官方网址：www.tancire.com
    proxy.$modal.msgError("请先选择添加的题目");
  }
}

/** 答题类型变化触发 */
function handleModelChange() {
  if (form.value.answerType === 1) {
    form.value.realAnswer = [];
  } else {
    form.value.realAnswer = '';
  }
}

watch(() => props.data.id, () => {
  queryParams.value.activityId = props.data.id;
  getList();
});

// 初始化查询参数
queryParams.value.activityId = props.data.id;
getList();
</script>
